package com.yyfax.ph.common.widgets.refreshview;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AbsListView;
import android.widget.ListView;

import com.yyfax.ph.R;

/**
 * 项目名称：YYLending
 * 类描述：上拉下拉刷新组件
 * 创建人：xiongyufeng
 * 创建时间：2016/11/15 15:39
 * 修改人：xiongyufeng
 * 修改时间：2016/11/15 15:39
 * 修改备注：
 */
public class LoadMoreRefreshLayout extends SwipeRefreshLayout implements AbsListView.OnScrollListener {
    /**
     * 滑动到最下面时的上拉操作
     */
    private int mTouchSlop;

    /**
     * listview实例
     */
    private ListView mListView;

    /**
     * 上拉监听器, 到了最底部的上拉加载操作
     */
    private OnLoadListener mOnLoadListener;

    /**
     * ListView的加载中footer
     */
    public View mListViewFooter;

    /**
     * 按下时的y坐标
     */
    private int mYDown;

    /**
     * 抬起时的y坐标, 与mYDown一起用于滑动到底部时判断是上拉还是下拉
     */
    private int mLastY;

    /**
     * 是否在加载中 ( 上拉加载更多 )
     */
    private boolean mIsLoading = false;

    private Context context;

    private boolean noMore=false;

    private boolean firstFlag=true;

    private boolean isMove=false;

    public void setNoMore(boolean noMore) {
        this.noMore = noMore;
    }

    public LoadMoreRefreshLayout(Context context) {
        this(context, null);
    }

    public LoadMoreRefreshLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context=context;
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        // 初始化ListView对象
        if (mListView == null) {
            getListView();
        }
    }

    /**
     * 获取ListView对象
     */
    private void getListView() {
        int childs = getChildCount();
        if (childs > 0) {
            View childView = this.getChildAt(1);
            if (childView instanceof ListView) {
                mListView = (ListView) childView;
                // 设置滚动监听器给ListView, 使得滚动的情况下也可以自动加载
                mListView.setOnScrollListener(this);
                Log.d(VIEW_LOG_TAG, "### 找到listview");
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        final int action = event.getAction();

        switch (action) {
			// 按下
            case MotionEvent.ACTION_DOWN:
                isMove=false;
                mYDown = (int) event.getRawY();
                break;
			// 移动
            case MotionEvent.ACTION_MOVE:
                mLastY = (int) event.getRawY();
                if ((mLastY-mYDown)>20){
                    isMove=true;
                }
                break;
			// 抬起
            case MotionEvent.ACTION_UP:
                isMove=false;
                if (canLoad()) {
                    loadData();
                }
                break;
            default:
                break;
        }
        return super.dispatchTouchEvent(event);
    }

    /**
     * 是否可以加载更多, 条件是到了最底部, listview不在加载中, 且为上拉操作
     */
    private boolean canLoad() {
        return isBottom() && !mIsLoading && isPullUp();
    }

    /**
     * 判断是否到了最底部
     */
    private boolean isBottom() {
        if (mListView != null && mListView.getAdapter() != null) {
            return mListView.getLastVisiblePosition() == (mListView.getAdapter().getCount() - 1);
        }
        return false;
    }

    /**
     * 是否是上拉操作
     */
    private boolean isPullUp() {
        return (mYDown - mLastY)*0.1 >= mTouchSlop;
    }

    /**
     * 如果到了最底部,而且是上拉操作.那么执行onLoad方法
     */
    private void loadData() {
        if (mOnLoadListener != null) {
            // 设置状态
            setLoading(true);
            mOnLoadListener.onLoad();
        }
    }

    public void setLoading(boolean loading) {
        mIsLoading = loading;
        if (firstFlag==true){
            firstFlag=false;
            if (!noMore){
                mListViewFooter = LayoutInflater.from(context).inflate(R.layout.idle_listview_footer, null, false);
                mListView.addFooterView(mListViewFooter);
            }
        }else{
            mListView.removeFooterView(mListViewFooter);
            if (!noMore){
                if (mIsLoading){//如果是正在加载
                    mListViewFooter = LayoutInflater.from(context).inflate(R.layout.loading_listview_footer, null, false);
                }else{
                    //显示"上拉加载更多"
                    mListViewFooter = LayoutInflater.from(context).inflate(R.layout.idle_listview_footer, null, false);
                }
                mListView.addFooterView(mListViewFooter);
            }else{
                if (mIsLoading){//如果是正在加载
                    mListViewFooter = LayoutInflater.from(context).inflate(R.layout.loading_listview_footer, null, false);
                    mListView.addFooterView(mListViewFooter);
                }
            }
        }
		mYDown = 0;
		mLastY = 0;
    }

    public void setOnLoadListener(OnLoadListener loadListener) {
        mOnLoadListener = loadListener;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        // 滚动时到了最底部也可以加载更多
    }

    /**
     * 加载更多的监听器
     */
    public interface OnLoadListener {
        void onLoad();
    }
}
